<?php

class BuildTreeController extends Controller
{   
    public $defaultAction = 'admin';
    public $layout='//layouts/admin';
	
    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules()
    {
        return array(
            array('allow',  // allow all users to perform 'index' and 'view' actions
                'actions'=>array('index','view'),
                'users'=>array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions'=>array('create','update'),
                'users'=>array('@'),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions'=>array('admin','delete'),
                'users'=>array('admin'),
            ),
//            array('deny',  // deny all users
//                'users'=>array('*'),
//            ),
        );
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id)
    {
        $xmlPath = Yii::getPathOfAlias('webroot').Package::XML_PACKAGE_PATH;
        $package = $this->loadModel($id);
        $config = simplexml_load_file($xmlPath.$package->file.'.xml');
       // var_dump($config);
        
        
        //$config = new SimpleXMLElement;        
        
        //var_dump($config->attributes());
        //echo $config->getName().'<br />';
        //$config->
        //$config = new DOMDocument;
        //$config->
        //$config->load($xmlPath.$package->file.'.xml');
        //var_dump($config->getElementsByTagName('package'));
       // $cur_package = new SimpleXMLElement($package_xml);
        //echo $package_xml->asXML();
        $this->render('view',array(
            'data'=>$this->loadModel($id),
            'config'=>$config
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate()
    {
        $xmlPath = Yii::getPathOfAlias('webroot').Package::XML_PACKAGE_PATH;
        $model=new Package;

        if(isset($_POST['Package']))
        {
            $model->attributes=$_POST['Package'];
            $model->cate_id = Yii::app()->getRequest()->getParam('category');
            $model->file = Package::convertVietNgu($model->cate_id.'_'.$_POST['Package']['name']);            
            $model->desc = $_POST['Package']['desc'];
            $model->create_by = Yii::app()->user->id;

            if($model->save()) {
                $root = Category::model()->findByPk($model->cate_id);
                $string = '<?xml version="1.0" encoding="UTF-8"?><package></package>';
                $package = new SimpleXMLElement($string);
                $package->addAttribute('type', Package::convertVietNgu($root->name));
                $package->addAttribute('id',$root->id);
                $subCates = $this->getSubCate($model->cate_id);
                foreach ($subCates  as $subCate) {
                    $element = Package::convertVietNgu($subCate['name']);
                    if($_POST['XML'][$element]!='') {
                    $current = $package->addChild($element,$_POST['XML'][$element]);
                    $current->addAttribute('id', $subCate['id']);
                    }
                }
                $package->asXML($xmlPath.$model->file.'.xml');
                
                $this->redirect(array('admin'));
          }
            }

        $this->render('create',array(
            'model'=>$model,
            'subcates'=>$this->getSubCate(Yii::app()->getRequest()->getParam('category'))
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id)
    {
        $xmlPath = Yii::getPathOfAlias('webroot').Package::XML_PACKAGE_PATH;
        $model=$this->loadModel($id);
        //$package = $this->loadModel($id);
        $config = simplexml_load_file($xmlPath.$model->file.'.xml');
        $attr = $config->attributes();
        //$category = Category::model()->findByPk($attr['id']);    

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if(isset($_POST['Package']))
        {
            $model->attributes=$_POST['Package'];
            $model->desc = $_POST['Package']['desc'];
            if($model->save()) {
                $root = Category::model()->findByPk($model->cate_id);
                $string = '<?xml version="1.0" encoding="UTF-8"?><package></package>';
                $package = new SimpleXMLElement($string);
                $package->addAttribute('type', Package::convertVietNgu($root->name));
                $package->addAttribute('id',$root->id);
                $subCates = $this->getSubCate($model->cate_id);
                foreach ($subCates  as $subCate) {
                    $element = Package::convertVietNgu($subCate['name']);
                    if($_POST['XML'][$element]!='') {
                    $current = $package->addChild($element,$_POST['XML'][$element]);
                    $current->addAttribute('id', $subCate['id']);
                    }
                }
                $package->asXML($xmlPath.$model->file.'.xml');
                
                $this->redirect(array('admin'));
          }
        }

        $this->render('update',array(
            'model'=>$model,
            'config'=>$config,
            'subcates'=>$this->getSubCate($attr['id'])
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id)
    {
        if(Yii::app()->request->isPostRequest)
        {
            // we only allow deletion via POST request
            $this->loadModel($id)->delete();

            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if(!isset($_GET['ajax']))
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
        }
        else
            throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Lists all models.
     */
    public function actionIndex()
    {
        $dataProvider=new CActiveDataProvider('Package');
        $this->render('index',array(
            'dataProvider'=>$dataProvider,
        ));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin()
    {
        
        
        $model=new Package('search');
        
        $model->unsetAttributes();  // clear any default values
        if(isset($_GET['Package']))
            $model->attributes=$_GET['Package'];

        $this->render('admin',array(
            'model'=>$model,
            'cate_root'=>$this->getSubCate(0)
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id)
    {
        $model=Package::model()->findByPk((int)$id);
        if($model===null)
            throw new CHttpException(404,'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model)
    {
        if(isset($_POST['ajax']) && $_POST['ajax']==='package-form')
        {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }
    
    public function actionTest()
	{       
            $xmlPath = Yii::getPathOfAlias('webroot').Package::XML_PACKAGE_PATH;
            $filename = 'test3';
            $filePath = $xmlPath.$filename.'.xml';
            
            $category = Category::model();
            $cate = Yii::app()->db->createCommand()
                              ->select()
                              ->from('category')
                              ->where('parent_id = 0')
                              ->queryAll();
                    ;             
             $nameXml = Package::convertVietNgu($cate[0]['name']);
             
             $string = '<?xml version="1.0" encoding="UTF-8"?><package></package>';
             $package = new SimpleXMLElement($string);
             $main = $package->addChild($nameXml);                      
             $components  = Yii::app()->db->createCommand()
                              ->select()
                              ->from('category')
                              ->where('parent_id = 1')
                              ->queryAll();
                    ;
             foreach ($components as $component) {
                        $componentName  = Package::convertVietNgu($component['name']);
                        $main->addChild($componentName,$component['name']);
                    }       
                    
             //$main->addChild('tes','sfsfs');
             $package->asXML($filePath);
             
            // echo $nameXml;
             
             //$doc = new SimpleXMLElement();
//            $doc = new DOMDocument("1.0","UTF-8");            
//            $main = $doc->createElement($nameXml);
//            $main->setAttribute('id',$cate[0]['id']);
//            
//            $component = $doc->createElement("abc",'oyeah');            
//            $main->appendChild($component);
//            $doc->appendChild($main);
//            // $abc = $doc->addChild('abc');
//            file_put_contents($filePath, $doc->saveHTML());

            //echo $doc->saveXML();

             
            
                    
            //$a = $this->convertVietNgu('ế chồng');
            //echo $a;
            
            //$xml->asXML($filePath);
            //echo $filePath;
            
            //$handle = fopen($filePath, 'w') or die('Cannot open file:  '.$filePath);


           // $xml = new SimpleXMLElement($str);
            //$xml->saveXML($filePath);
            
            //$xml = simplexml_load_file($filePath);
            
            $this->render('test');
	}
        public function getSubCate($cate_id=null) {
//            if($cate_id==null) {
//                return false;
//            }
//            else {
                $subCate = Yii::app()->db->createCommand()
                              ->select(array('id','name'))
                              ->from('category')
                              ->where('parent_id = '.$cate_id)
                              ->queryAll();
                    ;             
                if(null==$subCate)                    return FALSE;
                else                    return $subCate;
            
        }
        

	
}